/**
 * 联系表单提交处理
 */
class ContactForm {
    constructor() {
        this.form = document.getElementById('contactForm');
        this.submitBtn = document.getElementById('submitBtn');
        this.loadingSpinner = document.getElementById('loadingSpinner');
        this.successMessage = document.getElementById('successMessage');
        this.errorMessage = document.getElementById('errorMessage');
        
        this.init();
    }
    
    init() {
        if (this.form) {
            this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        }
    }
    
    async handleSubmit(e) {
        e.preventDefault();
        
        // 显示加载状态
        this.showLoading();
        
        // 收集表单数据
        const formData = new FormData(this.form);
        const data = {
            name: formData.get('name'),
            email: formData.get('email'),
            phone: formData.get('phone'),
            message: formData.get('message')
        };
        
        try {
            const response = await fetch('/api/contact', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            
            if (result.success) {
                this.showSuccess(result.message || '消息发送成功！');
                this.form.reset();
            } else {
                this.showError(result.error || '发送失败，请重试');
            }
        } catch (error) {
            console.error('提交错误:', error);
            this.showError('网络错误，请检查网络连接后重试');
        } finally {
            this.hideLoading();
        }
    }
    
    showLoading() {
        if (this.submitBtn) {
            this.submitBtn.disabled = true;
            this.submitBtn.innerHTML = '<i class="spinner-border spinner-border-sm me-2"></i>发送中...';
        }
    }
    
    hideLoading() {
        if (this.submitBtn) {
            this.submitBtn.disabled = false;
            this.submitBtn.innerHTML = '<i class="bi bi-send"></i> 发送消息';
        }
    }
    
    showSuccess(message) {
        this.hideMessages();
        if (this.successMessage) {
            this.successMessage.textContent = message;
            this.successMessage.style.display = 'block';
        }
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.hideMessages();
        }, 3000);
    }
    
    showError(message) {
        this.hideMessages();
        if (this.errorMessage) {
            this.errorMessage.textContent = message;
            this.errorMessage.style.display = 'block';
        }
    }
    
    hideMessages() {
        if (this.successMessage) {
            this.successMessage.style.display = 'none';
        }
        if (this.errorMessage) {
            this.errorMessage.style.display = 'none';
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new ContactForm();
});

// 表单验证
function validateForm() {
    const name = document.getElementById('name').value.trim();
    const email = document.getElementById('email').value.trim();
    const message = document.getElementById('message').value.trim();
    
    if (!name) {
        alert('请输入您的姓名');
        return false;
    }
    
    if (!email) {
        alert('请输入您的邮箱');
        return false;
    }
    
    if (!isValidEmail(email)) {
        alert('请输入有效的邮箱地址');
        return false;
    }
    
    if (!message) {
        alert('请输入消息内容');
        return false;
    }
    
    if (message.length > 2000) {
        alert('消息内容不能超过2000个字符');
        return false;
    }
    
    return true;
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 字符计数
function updateCharCount() {
    const messageTextarea = document.getElementById('message');
    const charCount = document.getElementById('charCount');
    
    if (messageTextarea && charCount) {
        const length = messageTextarea.value.length;
        charCount.textContent = `${length}/2000`;
        
        if (length > 2000) {
            charCount.style.color = 'red';
        } else if (length > 1800) {
            charCount.style.color = 'orange';
        } else {
            charCount.style.color = 'gray';
        }
    }
}

// 为消息输入框添加字符计数
document.addEventListener('DOMContentLoaded', () => {
    const messageTextarea = document.getElementById('message');
    if (messageTextarea) {
        messageTextarea.addEventListener('input', updateCharCount);
        updateCharCount(); // 初始化计数
    }
});
